package com.dunke.service.impl;

import com.dunke.core.common.Result;
import com.dunke.core.common.ResultPage;
import com.dunke.core.common.TokenData;
import com.dunke.core.dao.AdminLogDao;
import com.dunke.core.data.GetData;
import com.dunke.core.data.IpAddrData;
import com.dunke.core.data.PageData;
import com.dunke.core.data.admin.*;
import com.dunke.core.dto.AdminDto;
import com.dunke.core.dao.AdminDao;
import com.dunke.core.dto.AdminLogDto;
import com.dunke.core.enums.ReturnCode;
import com.dunke.service.AdminService;
import com.dunke.utils.DateUtils;
import com.dunke.utils.IpServletUtils;
import com.dunke.utils.JedisUtil;
import com.dunke.utils.TokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * (DbAdmin)表服务实现类
 *
 * @author makejava
 * @since 2021-06-23 18:22:53
 */
@Service("AdminService")
public class AdminServiceImpl implements AdminService {

    @Resource
    @Autowired
    private AdminDao adminDao;

    @Resource
    @Autowired
    private AdminLogDao logDao;

    @Autowired
    TokenUtil tokenUtil;

    /**
     * 用户登录
     * @param adminLogin
     * @return
     */
    @Override
    public Result login(AdminLogin adminLogin) {
        AdminDto adminDto = this.adminDao.login(adminLogin.getAccount());
        if (adminDto == null) {
            return Result.error(ReturnCode.USER_NOT_EXIST);
        } else if (!adminLogin.getPassword().equals(adminDto.getPassword())) {
            return Result.error(ReturnCode.USER_PASS_ERROR);
        }
        TokenData tokenData = new TokenData(adminDto.getId(),
                adminDto.getAccount(), adminDto.getPassword(), DateUtils.getCurrentMillis());
        // 生成Token
        String token = tokenUtil.getToken(tokenData);
        adminDto.setToken(token);
        adminDto.setPassword("");
        tokenData.setToken(token);
        JedisUtil jedisUtil = new JedisUtil();
        // 存储Token
        jedisUtil.setToken(tokenData);
        return Result.success(adminDto);
    }

    /**
     * 注册账户
     * @param register 实例对象
     * @return 是否成功
     */
    @Override
    public Result insert(AdminRegister register) {
        AdminDto  adminDto = this.adminDao.login(register.getAccount());
        if (adminDto != null) {
            return Result.error(ReturnCode.USER_HAVE_EXIST);
        }
        AdminInsert info = new AdminInsert();
        info.setAccount(register.getAccount());
        info.setPassword(register.getPassword());
        if (this.adminDao.insert(info) > 0) {
            return Result.success("注册成功");
        }
        return Result.error("注册失败");
    }

    /**
     * 修改密码
     * @param password
     * @return
     */
    @Override
    public Result updatePwd(AdminPassword password) {

        if (password.getType() > 2 && password.getType() < 1) {
            return Result.error("参数错误");
        }
        // 两次密码是否一致
        if (!password.getPassword().equals(password.getPasswordAgain())) {
            return Result.error(ReturnCode.PASSWORD_NOT_SAME);
        }
        // 修改密码时，旧密码不能为空
        if (password.getType() == 2 && StringUtils.isBlank(password.getOldPassword())) {
            return Result.error(ReturnCode.PASSWORD_NULL_OLD);
        }
        AdminDto adminDto = this.adminDao.login(password.getAccount());
        // 未找到用户
        if (adminDto == null) {
            return Result.error(ReturnCode.USER_NOT_EXIST);
        }
        // 旧密码错误
        if (password.getType() == 2 && adminDto.getPassword()
                .equals(password.getOldPassword())) {
            return Result.error(ReturnCode.USER_PASS_ERROR);
        }

        if (this.adminDao.updatePassword(password) > 0) {
            return Result.success("密码修改成功");
        }

        return Result.error("密码修改失败");
    }

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Result queryById(Integer id) {
        AdminDto adminDto = this.adminDao.queryById(id);
        if (adminDto == null) {
            return Result.error(ReturnCode.USER_NOT_EXIST);
        }
        adminDto.setPassword("");
        return Result.success(adminDto);
    }

    /**
     * 修改数据
     * @param info 实例对象
     * @return 是否成功
     */
    @Override
    public Result update(AdminInfo info) {
        if (this.adminDao.update(info) > 0) {
            return Result.success("用户信息修改成功");
        }
        return Result.error("用户信息修改失败");
    }

    /**
     * 查询多条数据
     *
     * @param paged 查询页数、每页条数
     * @return 对象列表
     */
    @Override
    public Result queryAllByLimit(PageData paged) {
        int offset = (paged.getPage() -1) * paged.getSize();
        int limit = paged.getSize();

//        PageHelper.startPage(1,3);
//        Page<AdminDto> datas = this.adminDao.queryAll();
//        PageInfo<AdminDto> pageInfo = new PageInfo<>(datas);
//        System.out.println("页码" + pageInfo.getPageNum());
        List<AdminDto> datas = this.adminDao.queryAllByLimit(offset, limit);
        if (datas == null) {
            return Result.success(new ResultPage<>(datas, paged.getPage(), 0, false));
        }
        return Result.success(new ResultPage<>(datas, paged.getPage(), datas.size(), datas.size() == limit));
    }

    /**
     * 通过主键删除数据
     * @param data 主键
     * @return 是否成功
     */
    @Override
    public Result deleteById(GetData data) {
        if (this.adminDao.delById(data.getId()) > 0) {
            return Result.success("用户删除成功");
        }
        return Result.error("用户删除失败");
    }

    /**
     * 退出登录
     * @param token
     * @return
     */
    @Override
    public Result loginOut(String token) {
        JedisUtil jedisUtil = new JedisUtil();
        if (jedisUtil.delete(token)) {
            return Result.success("退出登录成功");
        }
        return Result.error("退出登录失败");
    }

    /**
     * 写入登录log
     * @param data 登录信息
     * @return
     */
    @Override
    public Result insertLog(IpAddrData data) {
        if(data.getExist() == 0) {
            IpAddrData ipData = IpServletUtils.getIpData(data.getIp());
            data.setProvince(ipData.getProvince());
            data.setProvince(ipData.getCity());
        }
        if (this.logDao.insert(data) > 0){
            return Result.success("日志更新成功");
        }
        return Result.error("日志更新失败");
    }

    /***
     * 查询日志
     * @param paged 查询页数、每页条数
     * @param aid 管理员Id
     * @return
     */
    @Override
    public Result queryLogById(PageData paged, Integer aid) {
        int offset = (paged.getPage() -1) * paged.getSize();
        int limit = paged.getSize();
        List<AdminLogDto> logDto = this.logDao.queryAllById(aid, offset, limit);
        if (logDto == null) {
            return Result.success(new ResultPage<>(logDto, paged.getPage(), 0, false));
        }
        return Result.success(new ResultPage<>(logDto, paged.getPage(), logDto.size(), logDto.size() == limit));
    }

    /**
     * 删除日志
     * @param data
     * @param aid
     * @return
     */
    @Override
    public Result delLog(GetData data, Integer aid) {
        if (this.logDao.delLogById(data.getId(), aid) > 0) {
            return Result.success("日志删除成功");
        }
        return Result.error("日志删除失败");
    }
}
